from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Book, BookLoan
from .serializers import BookSerializer
from django.utils import timezone
from datetime import timedelta


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    @action(detail=True, methods=['post'])
    def borrow(self, request, pk=None):
        book = self.get_object()
        # user = request.user
        if book.quantity > 0:
            due_date = timezone.now().date() + timedelta(days=30)
            loan = BookLoan.objects.create(book=book, borrower=None, due_date=due_date)
            loan.save()
            book.quantity -= 1
            book.save()
            return Response({'message': f'书籍<<{book}>>借出成功'}, status=status.HTTP_200_OK)
        return Response({'message': '书籍不足'}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def return_book(self, request, pk=None):
        book = self.get_object()
        # user = request.user
        try:
            loan = BookLoan.objects.get(book=book, borrower=None, returned_date=None)
            loan.returned_date = timezone.now().date()
            loan.save()
            book.quantity += 1
            book.save()
            return Response({'message': f'书籍<<{book}>>归还成功'}, status=status.HTTP_200_OK)
        except BookLoan.DoesNotExist:
            return Response({'message': '书籍未借出'}, status=status.HTTP_400_BAD_REQUEST)
